package com.lanou3g.bbs.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    private static String url;
    private static String driverClass;
    private static Properties info = new Properties();

    static {
        InputStream fis = null;
        try {
            fis = JDBCUtil.class.getClassLoader().getResourceAsStream("JDBCProp.properties");
            info.load(fis);
            driverClass = info.getProperty("driverClass");
            url = info.getProperty("url");
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseAll.CloseA(fis);
        }
    }

    public static Connection getConn() {
        try {
            Connection conn = threadLocal.get();
            if (conn == null) {
                conn = DriverManager.getConnection(url, info);
            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void closeConn() {
        Connection conn = threadLocal.get();
        if (conn != null) {
            try {
                if (!conn.getAutoCommit()) {
                    conn.commit();
                }
                CloseAll.CloseA(conn);
                threadLocal.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void begin(){
        Connection conn=getConn();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
